﻿package bdz.common.effects{
	import bdz.common.events.GenericEvent;
	import flash.display.Shape;
	import flash.events.EventDispatcher;
	import flash.net.LocalConnection;
	import flash.utils.*;
	import flash.events.Event;
	
	public class RandomStringSequence extends EventDispatcher {
		
		private var inter:Number;
		private var str:String;
		private var speed:Number;
		private var prop:String;
		private var enterFramer:Shape;
		private var broken:Array;
		private var mytarget:Object;
		private var count:Number;
		private var rndr:Array = new Array();
		private var endcount:Number = 0;
		private var results:Array = new Array();
		private var stime:Number = 20;
		private var tmeout:Number;
		function RandomStringSequence(s:String, cnt:Number, ref:Object, p:String, sp:Number, gen:Number = 10 , lwcase:Boolean = false) {
			speed = sp;
			prop = p;
			count = cnt;
			str = s;
			mytarget = ref;
			stime = gen;
			broken = str.split("");
			clearTimeout(tmeout);
			tmeout = setTimeout(applyString, stime, 0, broken.length);
		}
		private function applyString(c:Number, e:Number) {
			if (c < e) {
				var sr:StringRandomizer = new StringRandomizer(Math.floor(Math.random() * 10) + count, broken[c], speed);
				sr.reference = c;
				sr.addEventListener(GenericEvent.CHANGE, applyChanges);
				sr.addEventListener(GenericEvent.COMPLETE, applyEnd);
				results[c] = "";
				c++;
				stime += 1;
				clearTimeout(tmeout);
				tmeout = setTimeout(applyString, stime, c, e);
			}
		}
		private function applyEnd(evt:GenericEvent):void {
			results[evt.target.reference] = evt.data;
			mytarget[prop] = results.slice().join("");
			if (endcount < broken.length) {
				endcount++;
			}else {
				broken = [];
				results = [];
			}
		}
		private function applyChanges(evt:GenericEvent):void {
			results[evt.target.reference] = evt.data;
			mytarget[prop] = results.slice().join("");
		}
	}
}